const API_URL = 'https://api.302.ai/v1/chat/completions';
const API_KEY = 'sk-z7jn9DgYAZ8I61RQZqMo8DLTO4VtmNt9ebkBEcVroY0UXc3v'; // 替换为你的实际 API 密钥  

export const chatWithAI = (aiModel, userMessage, onMessageReceived) => {
	return new Promise((resolve, reject) => {
		fetch(API_URL, {
				method: 'POST',
				headers: {
					'Authorization': `Bearer ${API_KEY}`,
					'Content-Type': 'application/json',
				},
				body: JSON.stringify({
					messages: [{
						role: 'user',
						content: userMessage
					}],
					model: 'gpt-4o-2024-11-20',
					stream: true,
				}),
			})
			.then(response => {
				if (!response.ok) {
					throw new Error(`Error: ${response.status}`);
				}
				return response.body.getReader();
			})
			.then(reader => {
				const decoder = new TextDecoder("utf-8");

				const readStream = () => {
					reader.read().then(({
						done,
						value
					}) => {
						if (done) {
							resolve();
							return;
						}

						const chunk = decoder.decode(value, {
							stream: true
						});
						const text = chunk.split("\n\n").filter(item => item.trim() !== "");

						text.forEach(item => {
							if (item.includes("[DONE]")) {
								resolve();
								return;
							}

							try {
								const streamObj = JSON.parse(
									`{${item.replace("data", "\"data\"")}}`);
								const content = streamObj.data.choices[0].delta
									.content;
								if (content) {
									onMessageReceived(content);
								}
							} catch (error) {
								console.error("Parsing error:", error);
							}
						});

						readStream();
					}).catch(error => {
						reject(`Stream reading failed: ${error}`);
					});
				};

				readStream();
			})
			.catch(error => {
				reject(`API Request Failed: ${error}`);
			});
	});
};

export default chatWithAI;